package com.guardian.command;

import com.guardian.command.util.CommandUtil;
import com.guardian.exception.InitializationException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 执行命令管理对象
 * @author: huwei
 * @date: 2019/10/10 15:42
 * @version: 1.0.0
 */
public class CommandManager {

    public static final String PRINT_HELP_WORD = "PRINT_HELP_WORD";

    /**
     * 命令执行器
     */
    private static Map<String , Command> executorCommandMap = new ConcurrentHashMap<>(16);

    /**
     * 启动命令执行器
     */
    private static Map<String , Command> startupCommandMap = new ConcurrentHashMap<>(16);

    /**
     * 命令初始化方法
     * @throws InitializationException
     */
    public static void initExecutorCommand() throws InitializationException {
        if(executorCommandMap.isEmpty()) {
            executorCommandMap = CommandUtil.loadCommand("executor");
        }
        if(startupCommandMap.isEmpty()) {
            startupCommandMap.putAll(CommandUtil.loadCommand("startup"));
        }
    }

    /**
     * 执行命令
     * @param command
     * @param args
     * @return 返回命令执行结果
     */
    public static String executorCommand(String command ,String ...args){
        return executeCommand(executorCommandMap ,command ,args);
    }

    /**
     * 启动执行命令
     * @param command
     * @param args
     * @return 返回命令执行结果
     */
    public static String startupCommand(String command ,String ...args){
        return executeCommand(startupCommandMap ,command ,args);
    }

    private static String executeCommand(Map<String ,Command> commandMap,String command ,String ...args){
        if(command == null || isPrintHelpWord(command) || commandMap.get(command.trim()) == null){
            return CommandUtil.helpCommand(startupCommandMap);
        }
        command = command.trim();
        Command commandExecutor = commandMap.get(command);

        return commandExecutor.exec(args);
    }

    private static boolean isPrintHelpWord(String command){
        return PRINT_HELP_WORD.equals(command);
    }
}
